<script setup lang="ts">
import {
  ref,
  defineProps,
  defineEmits,
  computed,
  reactive,
  onMounted
} from 'vue';
import {
  ElMessage,
  ElLoading,
  ElNotification,
  UploadProps,
  UploadUserFile
} from 'element-plus';
import {
  getDictDataType,
  addUserFileApi,
  getUserFileListApi,
  deleteUserFileApi
} from '@/api/user';
const props = defineProps({
  DictType: {
    type: String,
    default: function () {
      return '';
    }
  },
  fileList: {
    type: Array,
    default: function () {
      return [];
    }
  },
  userInfo: {
    type: Object,
    default: function () {
      return {};
    }
  }
});
let tabList = ref([]);
let uploadList = ref<any>([]);
let loading = reactive<any>(null);
let activeName = ref('');
const emit = defineEmits(['update:fileList']);

getTabList();
function getTabList() {
  getDictDataType(props.DictType).then(re => {
    tabList.value = re.response;
    tabList.value.forEach(function (item:any) {
      item.fileList = [];
    });
    activeName.value = re.response[0].dictCode;
  });
}

function getUserFileList() {
  getUserFileListApi({ userId: props.userInfo.userId }).then(re => {
    if (re.code === 1) {
      re.response.forEach(function (item:any) {
        tabList.value.forEach(function (items:any, index) {
          if (item.dictCode == items.dictCode) {
            items.fileList.push({
              name: item.fileUrl.split('/')[item.fileUrl.split('/').length - 1],
              url: item.fileUrl,
              id: item.id
            });
          }
        });
      });
    }
  });
}
onMounted(() => {
  setTimeout(() => {
    getUserFileList();
  }, 1000);
});

function uploadProgress() {
  loading = ElLoading.service({
    lock: true,
    text: '文件上传中…',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.5)'
  });
}

// 上传接口调取成功status为200
function uploadSuccess(res, file, fileList, item, index) {
  fileList.forEach(items => {
    items.dictCode = item.dictCode;
    items.dictIndex = index;
    items.type = items.raw?.type;
  });
  props.fileList[index] = fileList;
  // currentArr.push(file);
  // console.log(res);
  console.log(file);
  console.log(fileList);
  console.log(item);
  if (res.code === 1) {
    // 文件上传成功
    // ElNotification.success({
    //   title: '成功',
    //   message: `${file.name}文件上传成功！`
    // });
    addUserFile(
      {
        fileUrl: res.response,
        fileType: file.type,
        fileName: file.name,
        dictCode: file.dictCode,
        userId: props.userInfo.userId
      },
      fileList,
      file.uid
    );
    loading.close();
  } else {
    uploadError();
  }
}
function addUserFile(file, fileList, uid) {
  addUserFileApi(file).then(re => {
    if (re.code === 1) {
      fileList.forEach(function (item) {
        if (item.uid == uid) {
          item.id = re.response;
        }
      });
      ElNotification.success({
        title: '成功',
        message: `文件上传成功！`
      });
    } else {
      uploadError();
    }
  });
}
function uploadError() {
  loading.close();
  ElMessage.error('文件上传失败，请检查文件大小或文件格式');
}
function handleRemove(file, uploadFiles, item, index) {
  deleteUserFileApi({ ids: [file.id] }).then(re => {
    if (re.code === 1) {
      ElNotification.success({
        title: '成功',
        message: `文件删除成功！`
      });
    }
  });
}
</script>

<template>
  <el-tabs type="border-card" class="train-tab" v-model="activeName">
    <el-tab-pane v-for="(item, index) in tabList" :label="item.dictLabel" :name="item.dictCode" :key="index">
      <el-upload name="file" :data="{ folder: 'train/user' }"  accept="image/*" action="/api/upload/folder/file"
        v-model:file-list="item.fileList" :show-file-list="true"  :on-progress="uploadProgress" :on-remove="(file, uploadFiles) => {
      return handleRemove(file, uploadFiles, item, index);
    }
    " :on-success="(response, file, fileList) => {
      return uploadSuccess(response, file, fileList, item, index);
    }
    " :on-error="uploadError">
        <el-button type="primary" size="small" class="link-left wdd-button-mini">上传{{ item.dictLabel }}</el-button>
      </el-upload>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
    </el-tab-pane>
  </el-tabs>
</template>

<!--<style scoped lang="scss"></style>-->
